import 'package:changxindianzishangwu/cache/local_cache.dart';
import 'package:changxindianzishangwu/dao/sms_code_dao.dart';
import 'package:changxindianzishangwu/dao/user_info_dao.dart';
import 'package:changxindianzishangwu/provider/conversion.dart';
import 'package:changxindianzishangwu/provider/currentMessageList.dart';
import 'package:changxindianzishangwu/provider/friend.dart';
import 'package:changxindianzishangwu/provider/friendApplication.dart';
import 'package:changxindianzishangwu/provider/groupApplication.dart';
import 'package:changxindianzishangwu/provider/user.dart';
import 'package:changxindianzishangwu/util/app_color.dart';
import 'package:changxindianzishangwu/util/colors.dart';
import 'package:changxindianzishangwu/util/toast.dart';
import 'package:changxindianzishangwu/util/universal_view.dart';
import 'package:changxindianzishangwu/widget/app_bar.dart';
import 'package:changxindianzishangwu/widget/login_form_code.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

///修改密码=》获取验证码=>第二步

class UpdatePwdPage2 extends StatefulWidget {
  String code;

  UpdatePwdPage2(this.code, {Key key}) : super(key: key);

  @override
  _UpdatePwdPageState2 createState() => _UpdatePwdPageState2();
}

class _UpdatePwdPageState2 extends State<UpdatePwdPage2> {
  TextEditingController controller0;
  TextEditingController controller1;

  @override
  void initState() {
    // TODO: implement initState
    controller0 = TextEditingController();
    controller1 = TextEditingController();

    super.initState();
  }

  @override
  void dispose() {
    FocusScope.of(context).requestFocus(FocusNode());
    EasyLoading.dismiss();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: TopAppBar(context, "修改密码"),
      body: GestureDetector(
        onTap: (){
          FocusScope.of(context).requestFocus(FocusNode());
        },
        child: Container(
          color: Colors.white,
          padding: EdgeInsets.all(15),
          child: ListView(
            children: [
              Text(
                "设置6-18位的数字（数字+密码）",
                style:
                    TextStyle(color: AppColor.colorDefaultText, fontSize: sp(15)),
              ),
              Padding(
                padding: const EdgeInsets.only(top: 30),
                child: Text(
                  "设置密码",
                  style: TextStyle(fontSize: sp(13)),
                ),
              ),
              _inputPwd(controller0, "8-16位数字+字母"),
              Padding(
                padding: const EdgeInsets.only(top: 20),
                child: Text(
                  "确认密码",
                  style: TextStyle(fontSize: sp(13)),
                ),
              ),
              _inputPwd1(controller1, "再次输入密码"),
              UniversalView().line(),
              Padding(
                padding: const EdgeInsets.only(top: 50),
                child: UniversalView().longBtn("确认", () {
                  if (controller0.text.isEmpty || controller1.text.isEmpty) {
                    toast("请输入密码");
                    return;
                  }
                  if (controller0.text != controller1.text) {
                    toast("俩次密码不一致");
                    return;
                  }

                  if (!isPwd(controller0.text)) {
                    toast("密码长度必须为8-12位，英文+数字组合");
                    return;
                  }
                  _updatePwd();
                }),
              )
            ],
          ),
        ),
      ),
    );
  }
  bool passwordVisible0 = true;
  bool passwordVisible1 = true;

  _inputPwd(TextEditingController controller, String hint) {
    return TextField(
        obscureText: passwordVisible0,
        controller: controller,
        keyboardType: TextInputType.visiblePassword,
        cursorColor: Colors.greenAccent,
        decoration: InputDecoration(
            border: InputBorder.none,
            hintText: hint,
            hintStyle: TextStyle(
              fontSize: ScreenUtil().setSp(13),
              color: Color.fromRGBO(153, 153, 153, 1),
            ),
            suffixIcon: IconButton(
                onPressed: () {
                  setState(() {
                    passwordVisible0 = !passwordVisible0;
                  });
                },
                icon: Image.asset(
                  //根据passwordVisible状态显示不同的图标
                  passwordVisible0
                      ? "images/ic_n_see_pwd.png"
                      : "images/ic_see_pwd.png",
                  width: width(15),
                  height: width(15),
                ))),
        inputFormatters: [
          WhitelistingTextInputFormatter(
              RegExp("[a-zA-Z]|[0-9]")), //只能输入汉字或者字母或数字
          LengthLimitingTextInputFormatter(18), //最大长度
        ]);
  }
  _inputPwd1(TextEditingController controller, String hint) {
    return TextField(
        obscureText: passwordVisible1,
        controller: controller,
        keyboardType: TextInputType.visiblePassword,
        cursorColor: Colors.greenAccent,
        decoration: InputDecoration(
            border: InputBorder.none,
            hintText: hint,
            hintStyle: TextStyle(
              fontSize: ScreenUtil().setSp(13),
              color: Color.fromRGBO(153, 153, 153, 1),
            ),
            suffixIcon: IconButton(
                onPressed: () {
                  setState(() {
                    passwordVisible1 = !passwordVisible1;
                  });
                },
                icon: Image.asset(
                  //根据passwordVisible状态显示不同的图标
                  passwordVisible1
                      ? "images/ic_n_see_pwd.png"
                      : "images/ic_see_pwd.png",
                  width: width(15),
                  height: width(15),
                ))),
        inputFormatters: [
          WhitelistingTextInputFormatter(
              RegExp("[a-zA-Z]|[0-9]")), //只能输入汉字或者字母或数字
          LengthLimitingTextInputFormatter(18), //最大长度
        ]);
  }

  void _updatePwd() async {
    EasyLoading.show();
    int code = await UserInfoDao.userUpdatePwd(
        getUserInfo(), controller1.text, widget.code);
    EasyLoading.dismiss();
    if (code == 1) {
      setAppLoginToken("");
      onKickedOffline();
      Get.offAllNamed("/loginInit");
      return;
    }
    toast("修改密码失败");
  }

  void onKickedOffline() async {
// 被踢下线
    // 清除本地缓存，回到登录页TODO
    try {
      Provider.of<ConversionModel>(context, listen: false).clear();
      Provider.of<UserModel>(context, listen: false).clear();
      Provider.of<CurrentMessageListModel>(context, listen: false).clear();
      Provider.of<FriendListModel>(context, listen: false).clear();
      Provider.of<FriendApplicationModel>(context, listen: false).clear();
      Provider.of<GroupApplicationModel>(context, listen: false).clear();
      // 去掉存的一些数据
      Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
      SharedPreferences prefs = await _prefs;
      prefs.remove('token');
      prefs.remove('sessionId');
      prefs.remove('phone');
      prefs.remove('code');
    } catch (err) {
      print("someError");
      print(err);
    }
  }

  static bool isPwd(String input) {
    RegExp mobile = new RegExp(r"(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$");
    return mobile.hasMatch(input);
  }
}
